<template>
  <div class="content">
    <Tabs :value="sourceType" type="card" @on-click="tabClick">
      <TabPane label="全部客户" name="0"></TabPane>
      <TabPane label="手动录入" name="2"></TabPane>
      <TabPane label="案场营销" name="1"></TabPane>
    </Tabs>
    <div class="topRecord">
      <!-- <div class="record1">
        <p v-for="(item,index) in topRocerd" :key="index"
          :class="{'curr':topRocerdActive==index,'curr2':item.key=='waitAllocateClueCustomer'&&topRocerdData.waitAllocateClueCustomer>0}"
          @click="topRocerdClick(item,index)">
          <span>{{topRocerdData[item.key]}}</span><em>{{item.numText}}</em>
        </p>
      </div> -->
      <customTopListVue
        :fromType="'clueCustomer'"
        :topRocerdData="topRocerdData"
        @getClickData="getClickData" />
      <!-- <div class="recordBtn">
        <p>共有<span>{{visitTotal}}</span>个客户到访</p>
        <Button v-if="unlocking('0101020500')" type="info" ghost
          @click="goVisit">查看到访记录</Button>
      </div>
      <div class="recordBtn" v-if="unlocking('0101020800')">
        <p>共有<span>{{topRocerdData.wechatCustomer}}</span>个微信客户</p>
        <Button type="info" ghost @click="goWeChat">查看微信客户</Button>
      </div> -->
    </div>
    <div class="handles" style="margin-top: 5px">
      <Button
        type="primary"
        v-if="unlocking('0101020200') || unlocking('0101020700')"
        @click="toClueAllotPage">
        分配客户
      </Button>
      <Button type="primary" v-if="unlocking('0101020600')" @click="exportData('1')">导出</Button>
      <Button type="primary" v-if="unlocking('0101020100')" @click="exportData('0')">导出Excel</Button>
      <Button type="primary" @click="adjustHeader" v-if="unlocking('0101010300')">调整表头排序</Button>
      <Button type="primary" class="operation" v-if="unlocking('0101020900')" @click="operationClick">
        查看导出记录
      </Button>
      <!-- <Button type="primary" v-if="unlocking('0101020400')"
        @click="assignClueCustomersRecord">分配记录</Button> -->
      <!-- 大权限 小权限 分配客户 -->
      <Button type="primary">
        <a
          href="https://images.tospurfang.com/doc/%E7%BA%BF%E7%B4%A2%E5%AE%A2%E6%88%B7%E6%93%8D%E4%BD%9C%E6%8C%87%E5%BC%95.pdf"
          style="color: #fff"
          target="_blank">
          查看操作指引
        </a>
      </Button>
      <!-- <Checkbox v-model="careFlag" @on-change="careStatusChange"> 只看我关注的</Checkbox> -->
    </div>
    <dynamic-header
      ref="dynamicHeader"
      @fieldCancel="fieldCancel"
      @headUpdate="headUpdate"
      :sourcedata="sourcedata"
      :targetdata="targetdata"></dynamic-header>
    <dt-grid ref="table" :columns="columns" :page="page" :onFetch="onFetch" :cell-height="80" />
    <Modal
      v-model="detailsFlag"
      title="客户详情"
      width="80%"
      :styles="{ top: '5%' }"
      :footer-hide="true"
      @on-cancel="markCancel">
      <detail-page
        v-if="detailsFlag"
        :detailsParams="detailsParams"
        @distribution="distribution"
        @change="onDetailChange"></detail-page>
    </Modal>
    <allot-modal ref="allot" @detailsDistributeClue="detailsDistributeClue" />
    <preview-image :images="preViewImg" :showIndex="showIndex" ref="preViewImage"></preview-image>
    <operation-record ref="operationRecord"></operation-record>
  </div>
</template>

<script>
  import allotModal from '../assignCustomersRecord/components/allot-modal.vue'
  import detailPage from '../details.vue'
  import columnOpt from './opt/column'
  import clueCustomerMgr from '@/biz/customer/clueCustomer.js'
  import customerOptMgr from '@/biz/customer/customerOpt.js'
  import dynamicHeader from '@/components/dynamicHeader.vue'
  import receiverMgr from '@/biz/receiver/receiver'
  import customerMgr from '@/biz/customer/customer'
  import userMgr from '@/biz/user'
  import dt from '@dt/dt'
  import customTopListVue from '@/components/customTopList.vue'
  export default {
    components: {
      detailPage,
      dynamicHeader,
      allotModal,
      customTopListVue
    },
    data() {
      return {
        clickKey: '',
        showIndex: 0,
        preViewImg: [],
        hasAttention: null,
        careFlag: false, //关注的
        visitTotal: 0,
        sourceType: '0',
        sourcedata: [],
        targetdata: [],
        topRocerdData: {},
        topRocerd: [
          { key: 'allClueCustomer', numText: '全部客户' },
          { key: 'waitAllocateClueCustomer', numText: '待分配客户' }
          // { key: 'efficientClueCustomer', numText: '有效客户' },
          // { key: 'invalidClueCustomer', numText: '无效客户' }
        ],
        isEffectiveatistics: null,
        topRocerdActive: null,
        queryType: null, //统计待分配
        page: {
          total: 0,
          current: 1
        },
        validFlage: false,
        onRecordFlage: false,
        // 3.0
        columns: [],
        list: [],
        params: {},
        allClueNumber: 0,
        noHeretoNumber: 0,
        heretoNumber: 0,
        selected: [],
        userCustomerId: [],
        userCustomerIdRoute: [],
        popLoading: true,
        popClass: '',
        followUpList: [],
        popLen: 0,
        detailsFlag: false,
        detailsParams: {},
        // 电话
        callPopLoading: true,
        callPopClass: '',
        callList: [],
        userMess: userMgr.info()
      }
    },
    async mounted() {
      console.log('路由', this.$route)
      this.userCustomerIdRoute = this.$route.params.clueCustomerList
        ? this.$route.params.clueCustomerList
        : []
      this.customerChoosedLength = this.userCustomerIdRoute.length
      await this.getColumns()
      this.customerVisitRecord() //客户到访统计
      // clueCustomerMgr.getConsultant()
      clueCustomerMgr.selectTeamUser()

      clueCustomerMgr.getFilterOptions()
      clueCustomerMgr.getChannel()
      clueCustomerMgr.getArea()
      this.$refs.table.init(this)
      this.$refs.table.fetch()
    },
    methods: {
      // 获取点击顶部列表的key值
      getClickData(val) {
        console.log(val)
        this.queryType = val.queryType
        this.clickKey = val.queryType ? val.key : ''
        this.$refs.table.fetch(true)
      },
      //跳转分配客户详情
      toClueAllotPage() {
        this.$router.push({
          path: '/allCustomersManagement/clueAssign',
          query: {
            fromPage: 'clueCustomer',
            fromKey: this.clickKey
          }
        })
      },
      operationClick() {
        this.$refs.operationRecord.show('export_clueCustomer', 'M_5', this.$dt.buildInfo().housesId)
      },
      onDetailChange(val) {
        if (val && val.closeModal) {
          this.detailsFlag = false
        }
        this.$refs.table.fetch()
      },
      lookImg(val) {
        this.preViewImg = val
        this.$refs.preViewImage.show()
      },
      detailsDistributeClue() {
        this.detailsFlag = false
        this.$refs.table.fetch()
      },
      distribution(val) {
        this.$refs.allot.show('', '', val)
      },
      getChangeAttention(val) {
        let params = {
          buildingId: val.buildingId,
          roleId: userMgr.info().role.roleId,
          userCustomerId: val.userCustomerId,
          userId: this.userMess.userId
        }
        customerMgr.changeAttention(params).then((res) => {
          this.$Message.success(res == 1 ? '成功收藏该客户。' : '你取消收藏了该客户。')
          this.$refs.table.fetch()
        })
      },
      careStatusChange(val) {
        if (val) {
          this.hasAttention = 1
        } else {
          this.hasAttention = null
        }
        this.$refs.table.fetch()
      },
      assignClueCustomersRecord() {
        this.$router.push({
          path: '/allCustomersManagement/assignCustomersRecord'
        })
      },
      tabClick(val) {
        console.log(val)
        this.sourceType = val
        // this.queryType = null
        this.userCustomerId = []
        this.isEffectiveatistics = null
        this.topRocerdActive = null
        this.$refs.table.fetch(true)
      },
      initData() {
        this.$refs.table.fetch()
      },
      // 记录总数
      customerVisitRecord() {
        clueCustomerMgr.customerVisitRecord().then((res) => {
          this.visitTotal = res && res.length
        })
      },

      fieldCancel() {
        this.$refs.dynamicHeader.hide()
      },
      adjustHeader() {
        this.$refs.dynamicHeader.show()
      },
      goWeChat() {
        this.$router.push({
          path: '/allCustomersManagement/weChatCustomer',
          query: {}
        })
      },
      goVisit() {
        this.$router.push({
          path: '/allCustomersManagement/visitRecord',
          query: {}
        })
      },
      // 点击统计
      topRocerdClick(data, index) {
        this.userCustomerId = []
        this.queryType = null
        this.isEffectiveatistics = null
        if (data.key == 'efficientClueCustomer') {
          this.isEffectiveatistics = 1
        } else if (data.key == 'invalidClueCustomer') {
          this.isEffectiveatistics = 2
        } else if (data.key == 'waitAllocateClueCustomer') {
          this.queryType = 1
        }
        if (this.topRocerdActive == index) {
          this.topRocerdActive = null
        } else {
          this.topRocerdActive = index
        }
        this.$refs.table.fetch(true)
      },
      exportData(mask) {
        let params = {
          type: 1,
          dto: this.params,
          maskCustomerPhone: mask
        }
        params.dto.buildingId = dt.buildInfo().housesId
        clueCustomerMgr.clueListExport(params)
      },
      delHead(res, key) {
        let _index = res.resArr.findIndex((item) => {
          return item.dbKey == key
        })
        if (_index != '-1') {
          res.resArr.splice(_index, 1)
        }
        let _index1 = res.hiedHead.findIndex((item) => {
          return item.dbKey == key
        })
        if (_index1 != '-1') {
          res.hiedHead.splice(_index1, 1)
        }
        let _index2 = res.showHead.findIndex((item) => {
          return item.dbKey == key
        })
        if (_index2 != '-1') {
          res.showHead.splice(_index2, 1)
        }
      },
      //获取表头
      getColumns() {
        return customerOptMgr.columns(true, 1).then((res) => {
          if (res) {
            this.delHead(res, 'is_effective')
            this.delHead(res, 'feature_photo')
            this.columns = columnOpt.options(this, res.resArr, 'chooseBox')
            this.sourcedata = res.hiedHead
            this.targetdata = res.showHead
          }
        })
      },

      headUpdate(params) {
        params.type = 1
        clueCustomerMgr.clueHeadUpdate(params).then((res) => {
          this.getColumns()
          this.$nextTick(function () {
            this.$refs.dynamicHeader.hide()
          })
        })
      },

      // 获取统计数据
      getCount(data) {
        let params = {
          ...data,
          buildingId: dt.buildInfo().housesId
        }
        clueCustomerMgr.clueCustomerCount(params).then((res) => {
          this.topRocerdData = res
        })
      },
      // 列表数据
      onFetch(data) {
        if (this.userCustomerIdRoute.length) {
          this.userCustomerId = this.userCustomerIdRoute
          data.userCustomerId = this.userCustomerIdRoute
        }
        this.params = data
        this.params.hasAttention = this.hasAttention
        if (this.sourceType != '0') {
          this.params.networkCustomer = this.sourceType
        }
        this.getCount(this.params)
        // if (this.queryType == 1) {
        //   this.params.queryType = 1
        // }
        this.params.queryType = this.queryType
        if (this.isEffectiveatistics) {
          this.params.isEffective = this.isEffectiveatistics
        }
        this.params.buildingId = dt.buildInfo().housesId
        return clueCustomerMgr.clueCustomerList(data).then((res) => {
          res.records &&
            res.records.forEach((item) => {
              if (item.featurePhoto) {
                item.featurePhoto = item.featurePhoto.split(',')
              } else {
                item.featurePhoto = []
              }
            })
          this.list = res.records
          this.page.total = res.total
          return res.records
        })
      },

      // 查看详情
      viewClick(rows) {
        if (rows.hasCustomer) {
          this.detailsFlag = true
          this.detailsParams = {
            customerId: rows.customerId,
            userCustomerId: rows.bindingUserCustomerId ? rows.bindingUserCustomerId : rows.userCustomerId,
            buildingId: rows.buildingId,
            userId: rows.userId,
            buildingId: this.$dt.buildInfo().housesId,
            cityCode: this.$dt.buildInfo().cityId
          }
        } else {
          this.detailsFlag = true
          this.detailsParams = {
            hasAttention: true,
            assignBtn: true,
            flag: 'clue',
            customerId: rows.customerId,
            userCustomerId: rows.bindingUserCustomerId ? rows.bindingUserCustomerId : rows.userCustomerId,
            userId: rows.userId,
            buildingId: this.$dt.buildInfo().housesId,
            cityCode: this.$dt.buildInfo().cityId
          }
        }
      },
      markCancel() {
        this.detailsFlag = false
      },
      // 查询电话
      getCallList(val) {
        this.callPopLoading = true
        this.callPopClass = ''
        this.callList = []
        receiverMgr.callRecordList({ userCustomerId: val.userCustomerId }).then((res) => {
          this.callPopLoading = false
          this.callList = res.records
        })
      },
      // 查询跟进记录
      getFollowUp(val) {
        this.popLoading = true
        this.popClass = ''
        this.followUpList = []
        this.popLen = 0
        clueCustomerMgr
          .follow({
            page: 1,
            rows: 10,
            userCustomerId: val.userCustomerId,
            category: '4,12',
            customerId: val.customerId
          })
          .then((res) => {
            this.followUpList = res.records
            this.popLen = res.total
            this.updateFollow(val)
            this.popLoading = false
          })
      },

      // 更新跟进记录
      updateFollow(val) {
        clueCustomerMgr
          .updateFollow({
            userCustomerId: val.userCustomerId,
            customerId: val.customerId,
            category: '4'
          })
          .then((res) => {
            if (String(res) == 'true') {
              val.newNews = 2
            }
          })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .content {
    padding: 20px;

    .topRecord {
      display: flex;
      flex-direction: row;

      .record1 {
        display: flex;
        flex-direction: row;
        cursor: pointer;

        p {
          text-align: center;
          padding: 0 20px;

          span {
            display: block;
            font-size: 20px;
            font-weight: bold;
            color: #000;
          }

          em {
            display: block;
            font-style: normal;
          }
        }

        p.curr2 {
          span {
            color: red;
            font-weight: bold;
          }
        }

        p.curr {
          span {
            color: #2d8cf0;
            font-weight: bold;
          }
        }
      }

      .recordBtn {
        padding: 0 20px;

        border-left: 1px #ccc solid;

        p {
          span {
            color: #2db7f5;
          }
        }
      }
    }

    .retainClass {
      margin-top: 20px;
    }
  }

  .handles {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-bottom: 10px;

    > * {
      margin-left: 10px;
    }
  }

  .footer {
    text-align: center;
    margin-top: 20px;
    border-top: 1px #eee solid;
    padding-top: 20px;

    button {
      width: 80px;
      margin: 0 10px;
    }
  }
</style>
